package com.tensequare.friend.controller;

import com.netflix.discovery.converters.Auto;
import com.tensequare.friend.client.UserClient;
import com.tensequare.friend.service.FriendService;

import common.entity.Result;
import common.entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: Feng.Wang
 * @Company: Zelin.ShenZhen
 * @Description:
 * @Date: Create in 2019/3/29 15:56
 */
@RestController
@RequestMapping("/friend")
public class FriendController {
    @Autowired
    private UserClient userClient;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private FriendService friendService;
    @RequestMapping(value = "/like/{friendid}/{type}",method = RequestMethod.PUT)
    public Result addFriend(@PathVariable String friendid,@PathVariable String type){
        //1.从请求作用域中取出用户信息(查看拦截器)
        Claims claims = (Claims) request.getAttribute("user_claims");
        //2.判断
        if(claims == null){
            return new Result(false, StatusCode.ACCESSERROR,"没有权限");
        }

        if(type.equals("1")){  //喜欢
            int i = friendService.addFriend(claims.getId(), friendid);
            if(i == 0){
                return new Result(false, StatusCode.ERROR,"己经添加好友！");
            }

        }else if(type.equals("2")){//不喜欢
            friendService.addNoFriend(claims.getId(),friendid);
        }
        //修改关注数
        userClient.incFollowcount(1,claims.getId());
        //修改粉丝数
        userClient.incFanscount(1,claims.getId());
        return new Result(true, StatusCode.OK, "操作成功");

    }

    /**
     * 删除好友
     * @param friendid
     * @return
     */
    @RequestMapping(value = "/{friendid}",method = RequestMethod.POST)
    public Result deleteFriend(@PathVariable String friendid){
        //1.从请求作用域中取出权限
        Claims claims = (Claims) request.getAttribute("user_claims");
        //2.判断
        if(claims == null){
            return new Result(false, StatusCode.ACCESSERROR,"没有权限");
        }
        friendService.deleteFriend(claims.getId(),friendid);
        //更新关注数与粉丝数
        userClient.incFanscount(-1,claims.getId());
        userClient.incFollowcount(-1,claims.getId());
        return new Result(true,StatusCode.OK,"删除成功！");
    }

}
